package org.young.admin.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.young.common.utils.JsonUtil;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @doc
 */
@Configuration
public class LocalDateConfig {

	@Bean
	public ObjectMapper serializingObjectMapper() {
		ObjectMapper objectMapper = new ObjectMapper();
		SimpleModule module = new SimpleModule();
		module.addSerializer(LocalDate.class, new JsonUtil.LocalDateSerializer());
		module.addSerializer(LocalTime.class, new JsonUtil.LocalTimeSerializer());
		module.addSerializer(LocalDateTime.class, new JsonUtil.LocalDateTimeSerializer());
		module.addDeserializer(LocalDate.class, new JsonUtil.LocalDateDeserializer());
		module.addDeserializer(LocalTime.class, new JsonUtil.LocalTimeDeserializer());
		module.addDeserializer(LocalDateTime.class, new JsonUtil.LocalDateTimeDeserializer());
		objectMapper.registerModule(module);
		return objectMapper;
	}

	@Bean
	public Jackson2ObjectMapperBuilderCustomizer builderCustomizer() {
		DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		DateTimeFormatter dateTimeSerializeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		DateTimeFormatter dateTimeDeserializeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
		return builder -> {
			builder.serializerByType(Long.class, ToStringSerializer.instance);
			builder.serializerByType(LocalDate.class, new LocalDateSerializer(dateFormatter));
			builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeSerializeFormatter));
			builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeDeserializeFormatter));
		};
	}
}
